package mysql

import (
	"gorm.io/gorm"
)

type Goods struct {
	gorm.Model
	GoodsTitle  string  `gorm:"type:varchar(100);index;not null;comment:商品标题"`
	GoodsPrice  float32 `gorm:"type:decimal(10,2);not null;commit:商品价格;"`
	GoodsStock  int64   `gorm:"type:int(11);not null;commit:商品库存;"`
	GoodsStatus int64   `gorm:"type:tinyint(1);defer:1;not null;commit:商品状态;"`
	GoodsCover  string  `gorm:"type:varchar(255);commit:商品封面;"`
}

// 创建商品
func (g *Goods) Create() error {
	return DB.Create(&g).Error
}

// 模糊查询
func (g *Goods) List(keyword string, page int, size int) ([]*Goods, error) {
	var goodsList []*Goods
	err = DB.Where("goods_title like ?", "%"+keyword+"%").Scopes(Paginate(page, size)).Find(&goodsList).Error
	return goodsList, err
}

// 限制
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}
		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
